package cn.ecut.dao;

import cn.ecut.model.User;
import cn.ecut.util.JDBCUtil;
import cn.ecut.util.TableNames;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    public List<User> loadUsername(User user) throws SQLException {
        String password = user.getPassword();
        String username = user.getUserName();
        String sql = "select * from " + TableNames.USER_TABLE_NAME + " where username = ?";
        ResultSet resultSet = JDBCUtil.selectSQL(sql, username);
        return (warp(resultSet));
    }

    private List<User> warp(ResultSet resultSet) throws SQLException {
        List<User> list = new ArrayList<>();
        User user = new User();
        while (resultSet.next()) {
            user.setId(resultSet.getInt("id"));
            user.setUserName(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
            list.add(user);
        }
        return list;
    }

    public User loadByUserId( Integer  userId ){
        String SQL = "select id , username , password from" + TableNames.USER_TABLE_NAME + "where id = ? " ;
        ResultSet resultSet = JDBCUtil.selectSQL(SQL, userId);
        List<User> users = null;
        try {
            users = warp(resultSet);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if( users.size() > 0 ){
            return users.get( 0 ) ;
        }
        return null  ;
    }

    public boolean saveUser(User user ){
        String SQL = "insert into " + TableNames.USER_TABLE_NAME + "( username , password) values ( ? , ? )" ;
        return JDBCUtil.executeSQL( SQL , user.getUserName() , user.getPassword() ) ;
    }

}
